package com.yuyou.fn.updater.handler;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Optional;
import com.google.common.cache.LoadingCache;
import com.yuyou.fn.common.database.event.EventHandler;
import com.yuyou.fn.common.database.event.IEventHandler;
import com.yuyou.fn.common.util.CacheUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.Campus;
import com.yuyou.fn.educational.entity.ClassExpandDetail;
import com.yuyou.fn.educational.entity.Period;
import com.yuyou.fn.educational.entity.Teacher;
import com.yuyou.fn.educational.service.ICampusService;
import com.yuyou.fn.educational.service.IClassExpandDetailService;
import com.yuyou.fn.educational.service.IPeriodService;
import com.yuyou.fn.educational.service.ITeacherService;
import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.service.IAreaTeamService;
import com.yuyou.fn.portal.entity.OuterCourseClass;
import com.yuyou.fn.portal.repository.OuterCourseClassRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;

@EventHandler(tables = "yyfn.course_class")
@Component
public class OuterCourseClassUpdater implements IEventHandler {

    private static final Logger log = LoggerFactory.getLogger(OuterCourseClassUpdater.class);

    @Resource
    private IClassExpandDetailService classExpandDetailService;


    @Resource
    private ITeacherService teacherService ;


    @Resource
    private OuterCourseClassRepository courseClassRepository ;

    @Resource
    private ICampusService campusService;

    @Resource
    private IPeriodService periodService;

    private LoadingCache<Long,Optional<Teacher>> teacherLoadingCache ;

    private LoadingCache<Long,Optional<Campus>> campusLoadingCache  ;

    private LoadingCache<Long,Optional<Period>> periodCache  ;

    @PostConstruct
    public void init(){
        this.teacherLoadingCache = CacheUtils.buildCache(teacherService::findById) ;
        this.campusLoadingCache = CacheUtils.buildCache(campusService::findById) ;
        this.periodCache = CacheUtils.buildCache(periodService::findById) ;
    }

    @Override
    public void insert(String tableName, JSONArray rowList) {

        List<OuterCourseClass> courseClassList = toCourseClass(rowList, false );
        if(!courseClassList.isEmpty()){
            courseClassRepository.save(courseClassList);
        }
    }

    @Override
    public void update(String tableName, JSONArray rowList, Set<String> updateColumns) {

        List<OuterCourseClass> courseClassList = toCourseClass(rowList, false );
        if(!courseClassList.isEmpty()){
            courseClassRepository.save(courseClassList);
        }

    }

    @Override
    public void delete(String tableName, JSONArray rowList) {

        List<OuterCourseClass> courseClassList = toCourseClass(rowList, true );
        courseClassRepository.delete(courseClassList);

    }

    private List<OuterCourseClass> toCourseClass(JSONArray rowList , boolean isDelete) {
        List<OuterCourseClass> courseClassList = new ArrayList<>(rowList.size());
        for (int i = 0; i < rowList.size(); i++) {
            JSONObject row = processFiled(rowList.getJSONObject(i) );
            String areaTeamName = row.getString("areaTeamName");

            if(areaTeamName != null && areaTeamName.contains("测试")){
                continue;
            }
            OuterCourseClass courseClass = row.toJavaObject(OuterCourseClass.class);
                    /*if(courseClass.getStatus() != 1 ){
                        continue;
                    }*/


            if(!isDelete){
                try{
                    fillExtra(courseClass);
                }catch (Exception e){
                    log.error("fillExtra fail !" , e );
                    continue;
                }

            }

            int completedLectureAmount = row.getIntValue("completedLectureAmount");
            int  lectureAmount = row.getIntValue("lectureAmount");

            if(completedLectureAmount == lectureAmount ){//已经结课
                courseClass.setProgressStatus(2);
            }
            courseClassList.add(courseClass);
        }
        return courseClassList;
    }

    private JSONObject processFiled(JSONObject row) {
        JSONObject nRow = new JSONObject();
        for(String key : row.keySet()){
            nRow.put(Utils.camelCase(key),row.get(key));
        }
        return nRow ;
    }

    private void fillExtra(OuterCourseClass outerCourseClass) throws ExecutionException {

        ClassExpandDetail classExpandDetail=classExpandDetailService.findById(outerCourseClass.getClassId());
        if (classExpandDetail!=null){
            outerCourseClass.setChangeState(classExpandDetail.getChangeState()==null?1:classExpandDetail.getChangeState());
            outerCourseClass.setOnlineState(classExpandDetail.getOnlineState()==null?1:classExpandDetail.getOnlineState());
        }
        if(outerCourseClass.getTeacherId() != null ){

            Optional<Teacher> teacherOptional = teacherLoadingCache.get(outerCourseClass.getTeacherId());
            if(teacherOptional.isPresent()){
                Teacher teacher = teacherOptional.get();
                if (teacher.getJobNature()!=null && teacher.getJobNature()==1){
                    outerCourseClass.setTeacherName(outerCourseClass.getTeacherName().charAt(0)+"老师");
                }
                outerCourseClass.setAvatarUrl(teacher.getAvatarUrl());

            }

        }


        if (outerCourseClass.getCampusId() != null) {
            Optional<Campus> campusOptional = campusLoadingCache.get(outerCourseClass.getCampusId());
            if(campusOptional.isPresent()){
                Campus campus = campusOptional.get();
                String geoLocation = campus == null ? null : campus.getGeoLocation();
                if(StringUtils.isNotEmpty(geoLocation)){
                    String[] geoLocations = geoLocation.split(" ");
                    if (geoLocations.length >= 2) {
                        Point point = new Point(Double.parseDouble(geoLocations[0]), Double.parseDouble(geoLocations[1]));
                        outerCourseClass.setCampusLocation(point);
                    }
                }
                outerCourseClass.setCity(campus.getCity());
                outerCourseClass.setDistrict(campus.getDistrict());
                outerCourseClass.setCampusPhone(campus.getPhoneNo());
            }
        }

        outerCourseClass.setCampusAddress(outerCourseClass.getCampusName()+" "+outerCourseClass.getRoomName());



        //剩余名额
        outerCourseClass.setRemainingPlaces(outerCourseClass.getQuota()-outerCourseClass.getRegAmount());
        outerCourseClass.setTimeInterval(outerCourseClass.getClassDateTip());

        //满班状态
        outerCourseClass.setFullClassState(((outerCourseClass.getQuota()==null?0:outerCourseClass.getQuota())-(outerCourseClass.getRegAmount()==null?0:outerCourseClass.getRegAmount()))>0?0:1);

        Optional<Period> periodOptional = periodCache.get(outerCourseClass.getPeriodId());
        if(periodOptional.isPresent()){
            outerCourseClass.setPeriodNo(periodOptional.get().getPeriodNo());
        }

    }
}
